
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_user_id
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
from ...service.buss_pub.person_org_manage import PersonOrgManageService
# -*- coding: utf-8 -*-


class UserRelationShipObject():
    '''人员关系对象'''

    def __init__(self, main_relation_people, subordinate_relation_people, relationship_type_id):
        '''构造函数'''
        # 主关系id
        self.main_relation_people = main_relation_people
        # 关系人id
        self.subordinate_relation_people = subordinate_relation_people
        # 人员关系类型Id
        self.relationship_type_id = relationship_type_id

    def to_dict(self):
        return self.__dict__


"""
人员关系管理函数
"""


class UserRelationShipService(MongoService):
    """ 人员关系管理 """

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )
        self.person_org_manage_service = PersonOrgManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_user_relation_ship_list(self, condition, page, count):
        """获取人员关系列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        """
        keys = ["id", "type", "main_relation_people"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C("id") == values["id"]) & (C("type") == values["type"]) & (C("main_relation_people") == values["main_relation_people"]))\
            .lookup_bill('PT_User', 'subordinate_relation_people', 'id', 'family_person')\
            .add_fields({'family_person': '$family_person'})\
            .lookup_bill('PT_User_Relationship_Type', 'relationship_type_id', 'id', 'relation_type')\
            .add_fields({'relation_type_name': self.ao.array_elemat("$relation_type.name", 0)})\
            .add_fields({'relationShip_type': self.ao.array_elemat("$relation_type.type", 0)})\
            .sort({'create_date': -1})\
            .project({"_id": 0, "family_person._id": 0, "relation_type._id": 0})
        res = self.page_query(_filter, "PT_User_Relationship", page, count)
        print(res)
        return res

    def update_user_relation_ship(self, data):
        """ 新增人员关系 data: id,
                        user_id,
                        name,
                        id_card,
                        card_type,
                        sex,
                        date_birth,
                        native_place,
                        is_address_type,
                        address,
                        relationship_type_id,
                        telephone,
                        operation_type(长者、家属) """
        res = 'Fail'
        current_user_id = get_current_user_id(self.session)
        operation_type = OperationType.update.value
        data_info = []
        tables = ['PT_User', 'PT_User_Relationship']
        if 'id' in data.keys() and 'user_id' in data.keys():
            # 先更新PT_User表信息
            user_data = {}
            user_data['personnel_info'] = {}
            user_data['id'] = data['user_id']
            # 判断是否存在再赋值
            user_data['name'] = data['name']
            user_data['personnel_info']['sex'] = data['sex']
            user_data['personnel_info']['date_birth'] = data['date_birth']
            user_data['id_card'] = data['id_card']
            user_data['personnel_info']['id_card'] = data['id_card']
            user_data['personnel_info']['card_type'] = data['card_type']
            user_data['personnel_info']['native_place'] = data['native_place']
            user_data['personnel_info']['address'] = data['address']
            user_data['personnel_info']['telephone'] = data['telephone']
            user_data['personnel_info']['is_address_type'] = data['is_address_type']

            # 再更新PT_User_Relationship表信息
            user_relation_ship = UserRelationShipObject(
                current_user_id, data['user_id'], data['relationship_type_id']).to_dict()
            user_relation_ship['id'] = data['id']
            data_info = [user_data, user_relation_ship]
        else:
            operation_type = OperationType.add.value
            # 先判断长者（人员）是否存在
            _filter = MongoBillFilter()
            _filter.match_bill((C("id_card") == data["id_card"]))\
                .project({"_id": 0})
            res = self.query(_filter, "PT_User")
            subordinate_user = {}
            if len(res) > 0:
                # 存在，则更新长者（人员）信息（需要判断是长者还是家属）
                subordinate_user = res[0]
                if 'sex' in data.keys():
                    subordinate_user['personnel_info']['sex'] = data['sex']
                if 'date_birth' in data.keys():
                    subordinate_user['personnel_info']['date_birth'] = data['date_birth']
                if 'card_type' in data.keys():
                    subordinate_user['personnel_info']['card_type'] = data['card_type']
                if 'native_place' in data.keys():
                    subordinate_user['personnel_info']['native_place'] = data['native_place']
                if 'address' in data.keys():
                    subordinate_user['personnel_info']['address'] = data['address']
                if 'telephone' in data.keys():
                    subordinate_user['personnel_info']['telephone'] = data['telephone']
                if 'is_address_type' in data.keys():
                    subordinate_user['personnel_info']['is_address_type'] = data['is_address_type']
                self.person_org_manage_service.update_elder_info(
                    subordinate_user)
                # 判断长者关系是否已存在
                _filter = MongoBillFilter()
                _filter.match_bill((C("subordinate_relation_people") == subordinate_user["id"]) & (C("main_relation_people") == current_user_id))\
                    .project({"_id": 0})
                res_relation_ship = self.query(_filter, "PT_User_Relationship")
                if len(res_relation_ship) > 0:
                    # 存在关系则更新
                    operation_type = OperationType.update.value
                    user_relation_ship = UserRelationShipObject(
                        current_user_id, subordinate_user['id'], data['relationship_type_id']).to_dict()
                    user_relation_ship['id'] = res_relation_ship[0]['id']
                    user_relation_ship = get_info(
                        user_relation_ship, self.session)
                    data_info = [user_relation_ship]
                    tables = ['PT_User_Relationship']
                else:
                    # 不存在关系则新增PT_User_Relationship表信息
                    user_relation_ship = UserRelationShipObject(
                        current_user_id, subordinate_user['id'], data['relationship_type_id']).to_dict()
                    user_relation_ship = get_info(
                        user_relation_ship, self.session)
                    data_info = [user_relation_ship]
                    tables = ['PT_User_Relationship']
            else:
                # 不存在，则新增长者（人员）信息（需要判断是长者还是家属）
                user_object = {
                    'name': data['name'],
                    'personnel_type': '1',
                    'admin_area_id': data['admin_area_id'],  # 查询主关系人的行政区划
                    'id_card_type': '身份证',
                    'id_card': data['id_card'],
                    'organization_id': '',  # 查询主关系人的组织结构
                    'login_info': [{'login_type': 'account', 'login_check': {'account_name': ''}}],
                    'personnel_info': {
                        'name': data['name'],
                        "id_card": data['id_card'],
                        'personnel_category': '长者',
                        'personnel_classification': '',
                        'sex': data['sex'],
                        'telephone': data['telephone'],
                        'card_type': data['card_type'],
                        'date_birth': data['date_birth'],
                        'nation': '',
                        'native_place': data['native_place'],
                        'address': data['address'],
                        'card_number': '',
                        'remarks': '',
                        'role_id': '8ed260f6-e355-11e9-875e-a0a4c57e9ebe',
                        'family_name': '',
                        'card_name': '',
                        'id_card_address': '',
                        'guardian_name': '',
                        'guardian_id_card': '',
                        'guardian_date_birth': '',
                        'guardian_sex': '',
                        'guardian_age': '',
                        'guardian_dress': '',
                        'guardian_telephone': '',
                        'guardian_remarks': '',
                        'picture': [],
                        'is_address_type': data['is_address_type']
                    }
                }
                if 'operation_type' in data.keys():
                    user_object['personnel_info']['personnel_category'] = data['operation_type']
                # 查询当前登录人的信息
                user = self.person_org_manage_service.get_current_user_info()
                user_object['admin_area_id'] = user[0]['admin_area_id']
                user_object['organization_id'] = user[0]['organization_id']
                # user_info = get_info(user_object, self.session)
                # print('user_info>>>', user_info)
                add_user = self.person_org_manage_service.update_elder_info(
                    user_object)
                if add_user['res'] != 'Success':
                    return add_user
                # 再插入PT_User_Relationship表信息
                user_relation_ship = UserRelationShipObject(
                    current_user_id, add_user['id'], data['relationship_type_id']).to_dict()
                user_relation_ship = get_info(user_relation_ship, self.session)
                data_info = [user_relation_ship]
                tables = ['PT_User_Relationship']

        bill_id = self.bill_manage_service.add_bill(
            operation_type, TypeId.userRelationShip.value, data_info, tables)
        if bill_id:
            res = 'Success'
        return res

    def delete_user_relation_ship(self, user_relation_ship_ids):
        '''删除人员关系接口

        Arguments:
            user_relation_ship_ids   {ids}      数据id
        '''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            # ids = []
            # if isinstance(user_relation_ship_ids, str):
            #     ids.append(user_relation_ship_ids)
            # else:
            #     ids = user_relation_ship_ids
            # for user_relation_ship_ids in ids:
            print(user_relation_ship_ids)
            bill_id = self.bill_manage_service.add_bill(
                OperationType.delete.value, TypeId.userRelationShip.value, {'id': user_relation_ship_ids}, 'PT_User_Relationship')
            if bill_id:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_relationShip_type(self, condition, page, count):
        '''查询人员关系类型接口'''

        keys = ["id", "type", "name"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C("id") == values["id"]) & (C("name") == values["name"]) & (C("type") == values["type"]))\
            .project({"_id": 0})
        res = self.page_query(
            _filter, "PT_User_Relationship_Type", page, count)
        print(res)
        return res
